<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin;

use App\Middleware\JwtMiddleware;
use App\Middleware\ManagerRights;
use App\Model\Role;
use App\Resource\RoleCollection;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;

#[Controller]
class RoleController
{
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    #[Inject]
    protected RequestInterface $request;

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "", methods: "get")]
    /**
     * 列表
     * @return false|string
     */
    public function list()
    {
        $list = Role::query();
        if ($status = $this->request->input('status')) {
            $list->where('status', $status);
        }

        if ($keyword = $this->request->input('keyword')) {
            $list->keyword($keyword);
        }

        $list = $list->paginate((int)$this->request->input('page_num', 15));
        $data = [
            'list' => (new RoleCollection($list))->toListApi(),
            'count' => $list->total(),
            'count_page' => $list->lastPage(),
            'page_num' => $list->perPage(),
        ];

        return self::jsonResponse(200, 'success', $data);
    }


    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "add", methods: "post")]
    /**
     * 添加
     * @return false|string
     */
    public function add()
    {
        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'name' => [
                    'required',
                    Rule::unique('role')->where(function ($q) {
                        $q->whereNull('delete_time');
                    }),
                ],
                'rights' => 'required',
            ],
            [
                'name.required' => '请填写角色组名称',
                'name.unique' => '角色组已存在',
                'rights.required' => '请选择角色组操作权限',
//                'rights.array' => '获取角色组操作权限失败',
            ]
        );

        if ($data->fails()) {
            return self::jsonResponse(422, $data->errors()->first());
        }

        $data = $data->validated();
        $banner = new Role($data);
        $banner->manager()->associate(auth('manager')->user());
        $banner->save();

        return self::jsonResponse();
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "rights", methods: "get")]
    /**
     * 获取所有权限列表
     * @return false|string
     */
    public function allRights()
    {
        $list = config('rights.manager.rights');

        return self::jsonResponse(200, 'success', ['list' => $list]);
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "edit", methods: "post")]
    /**
     * 编辑
     * @return false|string
     */
    public function edit()
    {
        $id = $this->request->input('id');
        /** @var Role $role */
        $role = Role::getById($id);
        if (!$role) {
            return self::jsonResponse(404, '数据不存在');
        }

        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'name' => [
                    'required',
                    Rule::unique('role')->where(function ($q) use ($id) {
                        $q->whereNull('delete_time')->where('id', '!=', $id);
                    }),
                ],
                'rights' => 'required',
            ],
            [
                'name.required' => '请填写角色组名称',
                'name.unique' => '角色组已存在',
                'rights.required' => '请选择角色组操作权限',
//                'rights.array' => '获取角色组操作权限失败',
            ]
        );

        if ($data->fails()) {
            return self::jsonResponse(422, $data->errors()->first());
        }

        $data = $data->validated();
        $role->fill($data);
        $role->save();

        return self::jsonResponse();
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "handle", methods: "post")]
    /**
     * 启用/禁用
     * @return false|string
     */
    public function handle()
    {
        $id = $this->request->input('id');
        $role = Role::getById($id);
        if (!$role) {
            return self::jsonResponse(404, '数据不存在');
        }

        $role->handle();
        $role->save();

        return self::jsonResponse();
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "detail", methods: "get")]
    /**
     * 详情
     * @return false|string
     */
    public function detail()
    {
        $id = $this->request->input('id');
        $role = Role::getById($id);
        if (!$role) {
            return self::jsonResponse(404, '数据不存在');
        }

        return self::jsonResponse(200, 'success', $role->toApi());
    }

    #[Middleware(JwtMiddleware::class)]
    #[Middleware(ManagerRights::class)]
    #[RequestMapping(path: "delete", methods: "delete")]
    /**
     * 删除
     * @return false|string
     * @throws \Exception
     */
    public function delete()
    {
        $id = $this->request->input('id');
        $role = Role::getById($id);
        if (!$role) {
            return self::jsonResponse(404, '数据不存在');
        }

        if ($role->managers()->count() > 0) {
            return self::jsonResponse(400, '角色组下有管理员存在,不可删除');
        }

        $role->delete();

        return self::jsonResponse();
    }

    /**
     * 返回统一json
     * @param int $status
     * @param $message
     * @param $data
     * @param $headerStatus
     * @return false|string
     */
    public static function jsonResponse(int $status = 200, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
